package com.demo.sys.controller;

import com.demo.commons.DTO.Result;
import com.demo.commons.shiro.ShiroUtils;
import com.demo.commons.utils.Shiro2Utils;
import com.demo.sys.entity.SysUserEntity;
import com.demo.sys.entity.req.RequestLoginEntity;
import com.demo.sys.entity.resp.ResponseMenuListEntity;
import com.demo.sys.service.SysMenuService;
import com.demo.sys.service.SysUserService;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * <p>登入</p>
 *@author zwy
 *@date 2023/8/10 17:26
*/
@Api(tags = "登入")
@Controller
public class SysLoginController {
    @Autowired
    private Producer producer;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录
     */
    @ResponseBody
    @PostMapping(value = "/login")
    @ApiOperation(value = "平台登入")
    public Result login(@Validated @RequestBody RequestLoginEntity requestLoginEntity) {
        try {
            //账号 base64进行解密
            String account = new String(Base64.getDecoder().decode(requestLoginEntity.getAccount()));
            //验证
            String password = requestLoginEntity.getPassword();
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(account, password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return Result.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return Result.error("账号或密码不正确");
        } catch (LockedAccountException e) {
            return Result.error("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return Result.error("账户验证失败");
        }
        return Result.rule();
    }

    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }

    /**
     * 登录成功后进入index.html页面
     */
    @ApiOperation(value = "登入成功后进入首页")
    @GetMapping({"/index"})
    String index(Model model) {
        SysUserEntity sysUserEntity = ShiroUtils.getObject();
        List<ResponseMenuListEntity> menus = new ArrayList<>(16);
        if ("admin".equals(sysUserEntity.getAccount())) {
            menus = sysMenuService.getAdminMenuList(sysUserEntity.getType().toString());
            model.addAttribute("account", sysUserEntity.getAccount());
            model.addAttribute("name", sysUserEntity.getAccount());
            model.addAttribute("menus", menus);
            return "index";
        } else {
            menus = sysMenuService.getAdminMenuList(sysUserEntity.getGroupId().toString());
            model.addAttribute("account", sysUserEntity.getAccount());
            model.addAttribute("name", sysUserEntity.getAccount());
            model.addAttribute("menus", menus);
            //TODO:model打印
            System.out.println(model);
            return "index";
        }

    }

    /**
     * 修改后台系统管理员密码
     */
    @ResponseBody
    @RequestMapping("/updateSysPassword")
    public Result updateSysPassword(String oldPassword, String newPassword) {
        if (StringUtils.isBlank(oldPassword)) {
            return Result.error("旧密码不能为空!");
        }
        if (StringUtils.isBlank(newPassword)) {
            return Result.error("新密码不能为空!");
        }
        Long userId = ShiroUtils.getObject().getId();
        SysUserEntity sysUserEntity = sysUserService.getById(userId);
        String salt = sysUserEntity.getSalt();
        String oldPass = sysUserEntity.getPassword();
        if (!oldPass.equals(Shiro2Utils.sha256(oldPassword, salt))) {
            return Result.error("旧密码错误!");
        }
        String newpass = Shiro2Utils.sha256(newPassword, salt);
        sysUserEntity.setPassword(newpass);
        sysUserService.updateById(sysUserEntity);
        return Result.rule();
    }
}
